package great.project.param.config.convert;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.lang.NonNull;

import java.util.Date;
import java.util.regex.Pattern;

/**
 *  <div  style="border:2px solid none;margin:20px;padding:15px;font-size:24px;text-align:center;color:aqua;">
 *
 *  感觉没有直接 实现 Converter 来的方便
 *
 *  </div>
 * @author v_zhangshun01
 * @date 2021/11/26 4:21 下午
 */
public class StringToDateConverterFactory implements ConverterFactory<String, Date> {

    Pattern number = Pattern.compile("^[1-9]\\d*$");

    @NonNull
    @Override
    public <T extends Date> Converter<String, T> getConverter(@NonNull Class<T> targetType) {
        return source -> {
            if (number.matcher(source).find() && (source.length() == 13 || source.length() == 11)) {
                return (T) new Date(Long.parseLong(source));
            }
            return null;
        };
    }
}
